<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\Product;
use App\Models\Order;
use Carbon\Carbon;
use EasyWeChat;
use Log;

class ShoppingController extends ApiController
{

    /**
     * 添加购物车
     */
    public function addCart(Request $request)
    {
        $pid = $request->input('pid');  // 商品ID
        
        // 查询该商品
        $product = Product::published()->find($pid);
        if(!$product) {
            return $this->failed('商品不存在，或者已经下架');
        } else {
            $request->session()->put('cart', ['product' => ['id' => $product->id]]);
            return $this->message('添加成功');
        }
    }

    /**
     * 结算
     */
    public function checkOut(Request $request)
    {
        $aid =  $request->input('aid');

        $cart = $request->session()->get('cart');
        $product = Product::published()->with('shop')->findOrFail($cart['product']['id']);

        // 检查是否验证了手机号码
        if(empty(Auth()->user()->telphone)) {
            session(['http_referer' => route('shopping.checkOut')]);
            return redirect()->route('public.phoneVerification'); // 跳转验证号码
        }
        
        return view('front.shopping.checkOut', compact('product', 'aid'));
    }

    /**
     *  支付
     *
     * @return void
     */
    public function wxpay(Request $request, $id)
    {

        $order = Order::owner()->find($id);

        if (!$order) {
            return $this->failed('订单不存在');
        }

        if (!$order->status === Order::STATUS_UNPAID && !$order->payment_status === 'unpaid' ) {
            return $this->failed('订单不符合支付条件');
        }

        $amount = intval($order->order_amount_total * 100);
        if ($amount < 0) {
            return $this->failed('订单金额错误');
        }

        $attributes = [
            'trade_type' => 'JSAPI',
            'body' => $order->orderItems[0]->product_name,
            'detail' => $order->orderItems[0]->product_name,
            'out_trade_no' => $order->order_no,
            'total_fee' => $amount,
            'notify_url' => 'http://dev.cray.com',
            'openid' => $request->user()->openid,
            'attach' => $order->order_no
        ];

        $payment = EasyWeChat::payment();
        $result = $payment->order->unify($attributes);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];
            $order->prepay_id = $prepayId;
            $order->save();
        } else {
            Log::error('微信支付签名失败:'. var_export($result, 1));
            return $this->failed('发起支付失败');
        }

        $jssdk = $payment->jssdk->bridgeConfig($prepayId);
        return $this->success($jssdk);
    }
}
